//
//  XML.m
//  majorPatrol
//
//  Created by Loki Luo on 12-8-30.
//  Copyright (c) 2012年 I.F. All rights reserved.
//

#import "XML.h"

#define TIMEOUT                    5.0f


@implementation XML


// 初始化函数
- (id)init {
    return nil;     // 返回空，屏蔽默认的初始化
}


- (id)initWithData:(NSData*)xmlData {
    self = [super init];
    if ( self) {
        if ( nil == xmlData) {
            // 初始化失败
            NSLog(@"获取XML数据失败，传入数据为空！");
            return nil;
        }
        m_XMLParser = [[NSXMLParser alloc] initWithData:xmlData];
        if ( nil == m_XMLParser) {
            // 初始化失败
            NSLog(@"初始化XML数据失败！");
            return nil;
        }
        m_XMLParser.shouldProcessNamespaces = NO;
        m_XMLParser.shouldReportNamespacePrefixes = NO;
        m_XMLParser.shouldResolveExternalEntities = NO;
        m_XMLParser.delegate = self;
        // 创建数据对象
        _data = [[NSMutableDictionary alloc] initWithCapacity:0];
        m_arrDicList = [[NSMutableArray alloc] initWithCapacity:1];
        [m_arrDicList addObject:_data];
        // 解析XML
        if (![m_XMLParser parse]) {
            NSLog(@"XML解析失败，错误原因：%d！", [m_XMLParser parserError].code);
            return nil;
        }
    }
    return self;
}


- (id)initWithUrl:(NSString*)xmlUrl {
    if ( nil == xmlUrl || xmlUrl.length == 0) {
        NSLog(@"传入的地址无效！");
        return nil;
    }
    self = [super init];
    if ( self) {
        // 创建URL请求
        NSURL *url = [NSURL URLWithString:xmlUrl];
        NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
        if ( nil == req) {
            // 初始化失败
            NSLog(@"创建[URL:%@]连接失败！", xmlUrl);
            return nil;
        }
        [req setHTTPMethod:@"GET"];
        [req setTimeoutInterval:TIMEOUT];
        // 获取XML数据
        NSHTTPURLResponse *res = nil;
        NSError *err = nil;
        NSData *xmlData = [NSURLConnection sendSynchronousRequest:req 
                                             returningResponse:&res 
                                                         error:&err];
        if ( 200 != [res statusCode] || nil == xmlData) {
            // 初始化失败
            NSLog(@"获取XML数据失败，错误原因：%d！", [err code]);
            return nil;
        }
        // 初始化XMLParser
        m_XMLParser = [[NSXMLParser alloc] initWithData:xmlData];
        if ( nil == m_XMLParser) {
            // 初始化失败
            NSLog(@"初始化XML数据失败！");
            return nil;
        }
        m_XMLParser.shouldProcessNamespaces = NO;
        m_XMLParser.shouldReportNamespacePrefixes = NO;
        m_XMLParser.shouldResolveExternalEntities = NO;
        m_XMLParser.delegate = self;
        // 创建数据对象
        _data = [[NSMutableDictionary alloc] initWithCapacity:0];
        m_arrDicList = [[NSMutableArray alloc] initWithCapacity:1];
        [m_arrDicList addObject:_data];
        // 解析XML
        if ( ![m_XMLParser parse]) {
            NSLog(@"XML解析失败，错误原因：%d！", [m_XMLParser parserError].code);
            return nil;
        }
    }
    return self;
}


- (id)initWithFile:(NSString*)xmlFile {
    self = [super init];
    if ( self) {
        NSData *xmlData = [NSData dataWithContentsOfFile:xmlFile];
        if ( nil == xmlData) {
            // 初始化失败
            NSLog(@"从文件：[%@]读取XML数据失败！", xmlFile);
            return nil;
        }
        // 初始化XML
        m_XMLParser = [[NSXMLParser alloc] initWithData:xmlData];
        if ( nil == m_XMLParser) {
            // 初始化失败
            NSLog(@"初始化XML数据失败！");
            return nil;
        }
        m_XMLParser.shouldProcessNamespaces = NO;
        m_XMLParser.shouldReportNamespacePrefixes = NO;
        m_XMLParser.shouldResolveExternalEntities = NO;
        m_XMLParser.delegate = self;
        // 创建数据对象
        _data = [[NSMutableDictionary alloc] initWithCapacity:0];
        m_arrDicList = [[NSMutableArray alloc] initWithCapacity:1];
        [m_arrDicList addObject:_data];
        // 解析XML
        if ( ![m_XMLParser parse]) {
            NSLog(@"XML解析失败，错误原因：%d！", [m_XMLParser parserError].code);
            return nil;
        }
    }
    return self;
}


// Start
- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName 
    attributes:(NSDictionary *)attributeDict {
    // NSLog(@"START:%@", elementName);
    // 增加节点
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    if (nil != attributeDict && attributeDict.count > 0) {
        // 若节点包含属性，将属性加入其中
        [dic setObject:attributeDict forKey:kAttribute];
    }
    // 获取父节点
    NSMutableDictionary *pDic = [m_arrDicList lastObject];
    id sub = [pDic objectForKey:elementName];
    if ( nil != sub) {
        // 当对应名称的节点存在（存在同级同名节点）
        if ( [sub isKindOfClass:[NSMutableDictionary class]]) {
            // 该名字下只有一个节点，改用数组存同名节点
            NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
            [arr addObject:sub];
            [arr addObject:dic];
            [pDic setObject:arr forKey:elementName];
        }
        else {
            // 已存在数组节点，直接加入节点即可
            NSMutableArray *arr = (NSMutableArray*)sub;
            [arr addObject:dic];
        }
    }
    else {
        // 第一次加入该节点
        [pDic setObject:dic forKey:elementName];
    }
    [m_arrDicList addObject:dic];
}


// Found
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    // NSLog(@"VALUES:%@", string);
    if (nil != string && string.length > 0) {
        NSMutableCharacterSet *set = [[NSMutableCharacterSet alloc] init];
        [set formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        BOOL bHasValue = [string stringByTrimmingCharactersInSet:set].length > 0 ? YES : NO;
        if ( bHasValue) {
            NSMutableDictionary *pDic = [m_arrDicList lastObject];
            [pDic setObject:string forKey:kValue];
        }
    }
}


// End
- (void)parser:(NSXMLParser *)parser 
 didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName {
    // NSLog(@"END:%@", elementName);
    NSMutableDictionary *pDic = [m_arrDicList lastObject];
    [m_arrDicList removeLastObject];
    if (pDic.count == 0) {
        // 新加入的节点，没有任何子节点及赋值
        NSMutableDictionary *pDicParent = [m_arrDicList lastObject];
        [pDicParent removeObjectForKey:elementName];
    }
}


@end




